package com.bruip.ch01;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;

/**
 * @author yuxi
 * @version 1.0
 * @date 2025/10/22
 * @Description:
 */
public class Test09_Function {
    public static void main(String[] args) {


        String str="a-b-c-d-e-f-g";
        Function<String,String[]> f=new Function<String,String[]>() {
            @Override
            public String[] apply(String s) {
                return s.split("-");
            }
        };
        String[] arr=f.apply(str);
        for(String s:arr){
            System.out.println(s);
        }
        //传入String str,返回String[] 处理方式
        Function<String,String[]> f1=s->s.split("-");
        String[] arr1=f1.apply(str);
        for(String s:arr1){
            System.out.println(s);
        }
        System.out.println("==================");
        //传入数组 返回集合   处理方式：处理数组中的重复数据保存到集合中
        Function<String[], Set<String>> f2=array->{
            Set<String> set=new HashSet<>();
            for(String s:array){
                set.add(s);
            }
            return set;
        };
        String[] array={"a","b","c","d","e","f","g","a","b","c"};
        Set<String> set=f2.apply(array);
        for(String s:set){
            System.out.print(s);
        }
        System.out.println();
        System.out.println("==================");
        //将上面两个步骤合并
        Function<String,Set<String>> f3=f1.andThen(f2);
        String strr="a-b-c-d-e-f-g-a-b-c";
        Set<String> set1=f3.apply(strr);
        for(String s:set1){
            System.out.print(s);
        };
        System.out.println();
        System.out.println("===============");
        Function<String,Set<String>> f4=f2.compose(f1);
        Set<String> set2=f4.apply(strr);
        for(String s:set2){
            System.out.print(s);
        }
        Function<String,String> f5=Function.identity();
        String str1="hello world";
        String str2=f5.apply(str1);
        System.out.println(str2);
        //map应用
        Map<Integer,String> map=new HashMap<>();
        map.put(1,"hello");
        map.put(2,"world");
        Function<Integer,String> f6=key->"佚名";//
        String value=map.computeIfAbsent(2,f6);//存在就返回，不存在就调用f6函数添加，元素也会添加到map中
        String value1=map.computeIfAbsent(3,f6);
        System.out.println(value);
        System.out.println(value1);
        System.out.println(map);
        map.forEach((k,v)->System.out.println(k+":"+v));
    }
}
